package com.example.enews.adapters
import com.example.enews.databinding.ItemNewsBinding
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.ImageView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.example.enews.models.News
import android.content.Context
import androidx.recyclerview.widget.DiffUtil
import com.example.enews.R
class NewsAdapter(private val onItemClick: (News) -> Unit) :
    RecyclerView.Adapter<NewsAdapter.ViewHolder>() {

    private var newsList: List<News> = emptyList()

    fun submitList(list: List<News>) {
        val diffCallback = NewsDiffCallback(newsList, list)
        val diffResult = DiffUtil.calculateDiff(diffCallback)
        newsList = list
        diffResult.dispatchUpdatesTo(this)
    }

    class NewsDiffCallback(
        private val oldList: List<News>,
        private val newList: List<News>
    ) : DiffUtil.Callback() {

        override fun getOldListSize() = oldList.size
        override fun getNewListSize() = newList.size

        override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
            return oldList[oldItemPosition].id == newList[newItemPosition].id
        }

        override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
            return oldList[oldItemPosition] == newList[newItemPosition]
        }
    }


    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val binding = ItemNewsBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return ViewHolder(binding)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.bind(newsList[position])
    }

    override fun getItemCount(): Int {
        return newsList.size
    }

    inner class ViewHolder(private val binding: ItemNewsBinding) :
        RecyclerView.ViewHolder(binding.root) {
        fun bind(news: News) {
            binding.tvTitle.text = news.title
            binding.tvCategory.text = news.category
            binding.tvDate.text = news.date

            // 使用Glide标准API加载图片
            Glide.with(itemView.context)
                .load(news.imageUrl)
                .placeholder(R.drawable.placeholder_image)
                .error(R.drawable.error_image)
                .into(binding.ivNews)

            // 设置点击事件
            binding.root.setOnClickListener {
                onItemClick(news)
            }
        }
    }
}